import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Row, Col, Card, Button, Tabs, DatePicker, Alert, Tooltip, Form } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import Customer from '../../components/Customer';
import BillSupplier from '../../components/BillSupplier';
import DictCode from '../../components/DictCode';
import TextOverFlow from '../../components/TextOverFlow';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { MonthPicker } = DatePicker;

@connect(({ incexpcompcs, loading }) => ({
  pageData: incexpcompcs.pageData,
  loading: loading.models.incexpcompcs,
  tabList: incexpcompcs.tabList,
  expandForm: incexpcompcs.expandForm,
  activeKey: incexpcompcs.activeKey,
  formFieldsValue: incexpcompcs.formFieldsValue,
  valuesArr: incexpcompcs.valuesArr,
}))
class TableList extends PureComponent {
  formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      activeKey,
      formFieldsValue,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      dispatch({
        type: 'incexpcompcs/updateModalData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }

    dispatch({
      type: 'incexpcompcs/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  getSendSuppId = (_, options) => {
    if (options) {
      this.formRef.current.setFieldsValue({ sendSuppId: options });
    }
  };

  // 点击查询按钮
  searchBtnList = async activeKey => {
    const { valuesArr, dispatch } = this.props;
    try {
      const values = await this.formRef.current.validateFields([...valuesArr]);
      dispatch({
        type: 'incexpcompcs/updateModalData',
        payload: {
          formFieldsValue: values,
          activeKey,
        },
      });
      this.searchList(this.processFormData(values), activeKey);
    } catch (error) {
      console.error(error);
    }
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'incexpcompcs/updateModalData',
      payload: {
        values,
      },
    });

    if (activeKey === '1') {
      dispatch({
        type: 'incexpcompcs/fetchCustBillList',
        payload: {
          ...values,
        },
      });
    } else {
      dispatch({
        type: 'incexpcompcs/fetchSuppBillList',
        payload: values,
      });
    }
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'billYm') {
        tempFieldsValue[key] =
          (tempFieldsValue[key] && tempFieldsValue[key].format('YYYYMM')) || null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    return formFieldsValue;
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'incexpcompcs/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置
  resetSearch = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'incexpcompcs/updateModalData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue({ billYm: null });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { dispatch, formFieldsValue } = this.props;
    this.resetSearch();
    router.push(`/searchmanage/incexpcompcs/index?activeKey=${activeKey}`);
    dispatch({
      type: 'incexpcompcs/updateModalData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  renderSimpleForm() {
    const { activeKey, formFieldsValue } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '24px 0 0 0' }} bordered={false}>
        <Form initialValues={formFieldsValue} ref={this.formRef} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem name="custId" {...this.tableSearchLayout} label="客户名称">
                  <Customer allowClear />
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} name="sendSuppId" label="签约方">
                  <BillSupplier getData={this.getSendSuppId} allowClear />
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              <FormItem name="billYm" {...this.tableSearchLayout} label="账单年月">
                <MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <span>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开 <DownOutlined />
                </a>
              </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderAdvancedForm() {
    const { activeKey, formFieldsValue } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '24px 0 0 0' }} bordered={false}>
        <Form ref={this.formRef} initialValues={formFieldsValue} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem name="custId" {...this.tableSearchLayout} label="客户名称">
                  <Customer allowClear />
                </FormItem>
              ) : (
                <FormItem name="sendSuppId" {...this.tableSearchLayout} label="签约方">
                  <BillSupplier getData={this.getSendSuppId} allowClear />
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              <FormItem name="billYm" {...this.tableSearchLayout} label="账单年月">
                <MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem {...this.tableSearchLayout} name="budgState" label="实支状态">
                <DictCode dictType="BUDGET_STATE" allowClear />
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24} />
            <Col md={8} sm={24} />
            <Col md={8} sm={24}>
              <div style={{ overflow: 'hidden' }}>
                <span style={{ float: 'right', marginBottom: 24 }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={() => this.searchBtnList(activeKey)}
                  >
                    查询
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                    重置
                  </Button>
                  <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                    收起
                    <UpOutlined />
                  </a>
                </span>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { pageData, loading, tabList, activeKey } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const columns = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      // {
      //   title: '服务类型',
      //   dataIndex: 'serTypeName',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      // },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM')) || '--',
      },
      {
        title: '实支状态',
        dataIndex: 'budgStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensBudgStateName || '--'}
                </p>
                <p>
                  失业：
                  {record.unempBudgStateName || '--'}
                </p>
                <p>
                  工伤：
                  {record.injBudgStateName || '--'}
                </p>
                <p>
                  医疗：
                  {record.medBudgStateName || '--'}
                </p>
                <p>
                  生育：
                  {record.birthBudgStateName || '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthBudgStateName || '--'}
                </p>
                <p>
                  公积金：
                  {record.accuBudgStateName || '--'}
                </p>
              </div>
            }
          >
            <span>{(text && `${text}...`) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异金额',
        dataIndex: 'diffAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensDiffAmo || record.pensDiffAmo === 0 ? record.pensDiffAmo : '--'}
                </p>
                <p>
                  失业：
                  {record.unempDiffAmo || record.unempDiffAmo === 0 ? record.unempDiffAmo : '--'}
                </p>
                <p>
                  工伤：
                  {record.injDiffAmo || record.injDiffAmo === 0 ? record.injDiffAmo : '--'}
                </p>
                <p>
                  医疗：
                  {record.medDiffAmo || record.medDiffAmo === 0 ? record.medDiffAmo : '--'}
                </p>
                <p>
                  生育：
                  {record.birthDiffAmo || record.birthDiffAmo === 0 ? record.birthDiffAmo : '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthDiffAmo || record.insOthDiffAmo === 0 ? record.insOthDiffAmo : '--'}
                </p>
                <p>
                  公积金：
                  {record.accuDiffAmo || record.accuDiffAmo === 0 ? record.accuDiffAmo : '--'}
                </p>
              </div>
            }
          >
            <span>{text === 0 ? 0 : (text && `${text}...`) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异人数',
        dataIndex: 'diffNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: (text, record) => (
          <a
            onClick={() =>
              router.push(
                `/searchmanage/incexpcompcs/custbilldetail?activeKey=${activeKey}&budgId=${
                  record.budgId
                }`
              )
            }
          >
            查看
          </a>
        ),
      },
    ];
    const columnsSupply = [
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM')) || '--',
      },
      {
        title: '实支状态',
        dataIndex: 'budgStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensBudgStateName || '--'}
                </p>
                <p>
                  失业：
                  {record.unempBudgStateName || '--'}
                </p>
                <p>
                  工伤：
                  {record.injBudgStateName || '--'}
                </p>
                <p>
                  医疗：
                  {record.medBudgStateName || '--'}
                </p>
                <p>
                  生育：
                  {record.birthBudgStateName || '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthBudgStateName || '--'}
                </p>
                <p>
                  公积金：
                  {record.accuBudgStateName || '--'}
                </p>
              </div>
            }
          >
            <span>{(text && `${text}...`) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异金额',
        dataIndex: 'diffAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensDiffAmo || record.pensDiffAmo === 0 ? record.pensDiffAmo : '--'}
                </p>
                <p>
                  失业：
                  {record.unempDiffAmo || record.unempDiffAmo === 0 ? record.unempDiffAmo : '--'}
                </p>
                <p>
                  工伤：
                  {record.injDiffAmo || record.injDiffAmo === 0 ? record.injDiffAmo : '--'}
                </p>
                <p>
                  医疗：
                  {record.medDiffAmo || record.medDiffAmo === 0 ? record.medDiffAmo : '--'}
                </p>
                <p>
                  生育：
                  {record.birthDiffAmo || record.birthDiffAmo === 0 ? record.birthDiffAmo : '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthDiffAmo || record.insOthDiffAmo === 0 ? record.insOthDiffAmo : '--'}
                </p>
                <p>
                  公积金：
                  {record.accuDiffAmo || record.accuDiffAmo === 0 ? record.accuDiffAmo : '--'}
                </p>
              </div>
            }
          >
            <span>{text === 0 ? 0 : (text && `${text}...`) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异人数',
        dataIndex: 'diffNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: (text, record) => (
          <a
            onClick={() =>
              router.push(
                `/searchmanage/incexpcompcs/suppbilldetail?activeKey=${activeKey}&budgId=${
                  record.budgId
                }`
              )
            }
          >
            查看
          </a>
        ),
      },
    ];
    const custBill = (
      <div>
        <Alert
          style={{ margin: '16px auto' }}
          message={
            <span>
              实收数据来源于已收费的客户账单，实支数据本地执行的来源于已回盘的数据，供应商执行的来源于供应商已支付的付费账单，一个客户一个账单年月一条数据。
            </span>
          }
          type="info"
          showIcon
        />
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="budgId"
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const supplyBill = (
      <div>
        <Alert
          style={{ margin: '16px auto' }}
          message={
            <span>
              实收数据来源于已收费的供应商账单，实支数据本地执行的来源于已回盘的数据，供应商执行的来源于供应商已支付的付费账单，一个签约方一个账单年月一条数据。
            </span>
          }
          type="info"
          showIcon
        />
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="budgId"
          columns={columnsSupply}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 获取页签组件
    const getTabPane = key => {
      switch (key) {
        case '1':
          return custBill;
        case '2':
          return supplyBill;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard} bordered={false}>
          <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
            {tabList.map(pane => (
              <TabPane tab={pane.itemName} key={pane.itemCode}>
                <div className={styles.tableListForm}>{this.renderForm()}</div>
                {getTabPane(pane.itemCode)}
              </TabPane>
            ))}
          </Tabs>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
